<template>
  <div class="app-container">
    <form-filter @on-filter="submitFilterForm"/>
      <div class="batch-review">
        <el-button class="filter-item" type="primary"  @click="showAuditDialogBatch(1)" v-if="roleCheck('first-audit')">批量一审 </el-button>
        <el-button class="filter-item" type="primary"   @click="showAuditDialogBatch(2)" v-if="roleCheck('second-audit')">批量二审 </el-button>
      </div>
    <el-table border :data="tableData.list" v-loading="loading" element-loading-text="加载中..." ref="multipleTable" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" v-if="roleCheck('first-audit')||roleCheck('second-audit')"></el-table-column>
      <el-table-column label="操作类型" prop="optType" align="center" width="160" class="optType">

        <template slot-scope="{row}">
          {{ row.optDesc}}
        </template>
      </el-table-column>
      <el-table-column label="操作内容" align="center">
         <el-table-column label="修改前内容" prop="optBeforeData" width="120" align="center">
            <!--<template slot-scope="{row}">-->
          <!--{{ getOptData(row,1)}}-->
        <!--</template>-->
        </el-table-column>
        <el-table-column label="修改后内容" prop="optAfterData" width="120" align="center">
           <template slot-scope="{row}">
          {{ row.optAfterData === '' ? getOptData(row) : row.optAfterData}}
        </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="账户名" prop="username" align="center" width="120">
      </el-table-column>
      <!--<el-table-column label="账户类型" prop="userType" align="center" width="120">-->
      <!--<template slot-scope="{row}">-->
      <!--{{ row.userType | toConverter('ACCOUNT_TYPE') }}-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column label="申请人" prop="creator" align="center" width="120">
      </el-table-column>
      <el-table-column label="申请时间" prop="createTime" align="center">
        <template slot-scope="{row}">
          {{row.createTime | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="一审状态" fixed="right" prop="auditFirStatus" align="center" width="100">
        <template slot-scope="{row}">
          <el-button type="text" v-if="row.status === 2" @click="roleCheck('first-audit')?showAuditDialog(row,1):null" :style="{color:roleCheck('first-audit')?'#409eff':'#666'}">审核未通过</el-button>
          <el-button type="text" v-else-if="row.status === 0" @click="isPermissionMehod('first-audit', 0, row)" :style="isPermissionCss('first-audit', 0, row)">待审核</el-button>
          <el-button type="text" v-else @click="roleCheck('first-audit')?showAuditDialog(row,1):null" :style="{color:roleCheck('first-audit')?'#409eff':'#666'}">审核通过</el-button>
        </template>
      </el-table-column>
      <el-table-column label="一审人" fixed="right" prop="firstApprover" align="center" width="100">
      </el-table-column>
      <el-table-column label="审核时间" fixed="right" prop="firstTime" align="center" width="160">
        <template slot-scope="{row}">
          {{row.firstTime | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="二审状态" fixed="right" align="center" width="100">
        <template slot-scope="{row}" v-if="row.status === 1 || row.status>2">
          <el-button type="text" v-if="row.status === 3" @click="roleCheck('second-audit')?showAuditDialog(row,2):null" :style="{color:roleCheck('second-audit')?'#409eff':'#666'}">审核通过</el-button>
          <el-button type="text" v-else-if="row.status === 4" @click="roleCheck('second-audit')?showAuditDialog(row,2):null" :style="{color:roleCheck('second-audit')?'#409eff':'#666'}">审核未通过</el-button>
          <el-button type="text" v-else-if="row.status === 1" @click="isPermissionMehod('second-audit', 1, row)" :style="isPermissionCss('second-audit', 1, row)">待审核</el-button>
        </template>
      </el-table-column>
      <el-table-column label="二审人" fixed="right" prop="secondApprover" align="center" width="100">
      </el-table-column>
      <el-table-column label="审核时间" fixed="right" prop="secondTime" align="center" width="160">
        <template slot-scope="{row}">
          {{ row.secondTime | toTime}}
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="gridSizeChange" @current-change="gridCurrentChange"
                     :current-page="filters.page" :page-sizes="gridPageSize" :page-size="filters.size"
                     :layout="gridLayout" :total="tableData.total">
      </el-pagination>
    </div>
    <audit-dialog
      v-model="auditDialogVisible"
      v-if="auditDialogVisible"
      :row-data="rowData"
      :id="rowData.id"
      :audit-step="auditStep"
      :menuId="menuId"
    />
    <audit-dialog-multi
      v-model="auditDialogVisibleMulti"
      v-if="auditDialogVisibleMulti"
      :row-data="rowData"
      :id="ids"
      :audit-step="auditStep"
      :menuIds="menuIds"
    />
  </div>
</template>


<script>
import { getAuditList } from '@/services/api/audit';
import FormFilter from './formFilter';
import AuditDialog from '@/views/member/updateAudit/auditDialog';
import AuditDialogMulti from '@/views/member/updateAudit/auditDialogMulti';
import { grid } from '@/build';

export default {
  name: 'member-audit',
  components: { AuditDialog, FormFilter, AuditDialogMulti },
  mixins: [grid],
  data() {
    return {
      ids: [], // 批量审核的id数组
      tableData: {},
      auditStep: 0,
      rowData: {},
      rowDataList: [], // 批量审核选中的数据
      auditDialogVisible: false,
      auditDialogVisibleMulti: false, // 是否显示批量审核确认框

      filters: {
        userType: 0,
        dateType: 0,
        page: 1,
        size: 20,
        status: -1,
        startDate: moment().format('YYYY-MM-DD 00:00:00'),
        endDate: moment().format('YYYY-MM-DD 23:59:59'),
      },
      filterDateType: false,
      dataPermissionObj: {
        1: ['memChangeSuperiorAgency-firstAudit', 'memChangeSuperiorAgency-secondAudit'],
        2: ['memChangeContact-firstAudit', 'memChangeContact-secondAudit'],
        3: ['memResetBankCardName-firstAudit', 'memResetBankCardName-secondAudit'],
        4: ['memWholeLock-firstAudit', 'memWholeLock-secondAudit'],
        5: ['memIndirectLock-firstAudit', 'memIndirectLock-secondAudit'],
        6: ['memUnLock-firstAudit', 'memUnLock-secondAudit'],
        17: ['memLoginLock-firstAudit', 'memLoginLock-secondAudit'],
        8: ['memDeleteBank-firstAudit', 'memDeleteBank-secondAudit'],
        12: ['memClearFlowLimit-firstAudit', 'memClearFlowLimit-secondAudit'],
        108: ['memAdjustFlow-firstAudit', 'memAdjustFlow-secondAudit'],
        109: ['memRemoveFlow-firstAudit', 'memRemoveFlow-secondAudit'],
        110: ['memRecoverFlow-firstAudit', 'memRecoverFlow-secondAudit'],
      },
      menuId: '',
      menuIds: [],
    };
  },
  methods: {
    // 表格前面的checkbox操作
    handleSelectionChange(val) {
      this.rowDataList = val;
    },

    /*
       * step:
       * 1.批量一审
       * 2.批量二审
       */
    showAuditDialogBatch(step) { // 批量审核
      if (this.ids.length === 0 && !this.rowData) {
        this.$message({
          type: 'warning',
          message: '请选中需要处理的数据',
        });
        return;
      }
      this.auditStep = step;
      this.ids = [];
      this.menuIds = [];
      let flag = false;

      if (this.auditStep == 1) { // 批量一审
        this.rowDataList.forEach((element) => {
          if (element.status == 0) {
            flag = true;
            this.rowData = element;
            this.ids.push(element.manageId);
            this.menuIds.push(element.firstMenuId);
          }
        });
        if (!flag) {
          this.$message({
            type: 'warning',
            message: '没有需要一审的操作,请重新选择数据',
          });
          return;
        }
      } else if (this.auditStep == 2) { // 批量二审
        this.rowDataList.forEach((element) => {
          if (element.status == 1) {
            flag = true;
            // console.log(`element.status${element.status}`);
            // console.log(`this.rowData${JSON.stringify(this.rowData)}`);
            this.rowData = element;
            this.ids.push(element.manageId);
            this.menuIds.push(element.secondMenuId);
          }
        });
        if (!flag) {
          this.$message({
            type: 'warning',
            message: '没有需要二审的操作,请重新选择数据',
          });
          return;
        }
      }
      this.auditDialogVisibleMulti = true;
    },
    submitFilterForm(formInline) {
      const { time } = formInline;
      let startDate; let
        endDate;
      if (!_.isUndefined(time) && _.isArray(time)) {
        startDate = time[0];
        endDate = time[1];
        formInline = { ...formInline, startDate, endDate };
      } else {
        this.filters.startDate = undefined;
        this.filters.endDate = undefined;
      }
      this.filters = { ...this.filters, ...formInline };
      this.gridSearch();
    },
    showAuditDialog(row, step, menuId) {
      this.auditDialogVisible = true;
      this.rowData = row;
      this.auditStep = step;
      this.menuId = menuId;
    },
    getOptData(row, type) {
      const { optType, optData, optBeforeData } = row;
      const contentData = (type && type === 1) ? optBeforeData : optData;
      switch (optType) {
        case 1:
          return `上级代理${row.username}：${contentData}`;
        case 2:
          return `修改：${this.formatPhoneEmail(contentData)}`;
        case 3:
          return '重置银行卡及姓名';
        case 4:
          return '状态修改：完全锁定';
        case 5:
          return '状态修改：间接锁定';
        case 6:
          return '状态修改：解除锁定';
        case 7:
          return `返佣模式：${contentData}`;
        case 8:
          return `银行卡ID：${contentData}`;
        case 9:
          return `修改备注：${contentData}`;
        case 10:
          const optDataArr = contentData.split(',');
          return `额度：${optDataArr[0]}，状态：${_.toConverter(parseInt(optDataArr[1]), 'AGENCY_CREDIT_STATUS')}`;
        default:
          return contentData;
      }
    },
    formatPhoneEmail(val) {
      let res = '';
      if (val && val != '') {
        const phoneShowPartial = this.roleCheck('phone-show-partial');
        const phoneShowAll = this.roleCheck('phone-show-all');
        const emailShowPartial = this.roleCheck('email-show-partial');
        const emailShowAll = this.roleCheck('email-show-all');
        if (val.indexOf(',') > -1) {
          const arr = val.split(',');
          if (arr.length > 2) {
            res = `${arr[0]},${_.formatUserPhoneEmail(arr[1], phoneShowPartial, phoneShowAll)},
                    ${_.formatUserPhoneEmail(arr[2], emailShowPartial, emailShowAll)}`;
          } else {
            res = _.formatUserPhoneEmail(arr[1], phoneShowPartial, phoneShowAll);
          }
        } else {
          res = _.formatUserPhoneEmail(val, emailShowPartial, emailShowAll);
        }
      }
      return res;
    },
    isPermissionMehod(audit, num, row) {
      const menuId = num === 0 ? row.firstMenuId : row.secondMenuId;
      return this.roleCheck(audit) && this.dataRoleCheck(this.dataPermissionObj[row.optType][num]) ? this.showAuditDialog(row, num + 1, menuId) : null;
    },
    isPermissionCss(audit, num, row) {
      return { color: this.roleCheck(audit) && this.dataRoleCheck(this.dataPermissionObj[row.optType][num]) ? '#409eff' : '#666' };
    },
  },
  mounted() {
    this.bindGet(getAuditList, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
      format: (data) => {
        data.list.forEach((item) => {
          item.firstMenuId = dataPermission.DATA_PERMISSION[this.dataPermissionObj[item.optType][0]];
          item.secondMenuId = dataPermission.DATA_PERMISSION[this.dataPermissionObj[item.optType][1]];
        });
        return data;
      },

    });
    this.getAll();
  },
};
</script>

<style scoped>
  .batch-review{padding:10px 0}
</style>
